# -*- coding: utf-8 -*-
"""
Created on Mon Sep  8 10:47:48 2025

@author: huangyue
"""

import datetime
import pandas as pd
# import numpy as np
from numpy import nan
import pymssql


import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

# 连接聚源的参数
server_jydb = "10.10.0.102"
user_jydb = "jydb"
password_jydb = "jydb"

# 连接infodb的参数
server_zs = "infodb"

d1 = datetime.timedelta(days=1)

import os
import sys
sys.path.append("..")
from lib.get_anadata import anadata
# from lib.get_anadata import cmp_data
# from lib.get_anadata import CBinfo
# from lib.utils import get_premiumdata
from lib.utils import get_enddate
# from lib.getCBData_infodb import get_his_adjpremiumRate


# %%
'''提取持仓数据'''
def get_holding_data(cursor,FInnerCode, assetType,begdate,enddate=None):
    str_columns = 'FDate, FInnerCode, AccountCode, AccountName, SecCode, Volumn'.replace(' ','')  # 删除所有空格
    list_columns = str_columns.split(',')
    
    strFInnerCode = str(FInnerCode)
    
    if assetType == 'stock':
        assetsql = '''
                 (AccountCode like '1102.01.01.%%'   --上交所股票
                  or AccountCode like '1102.2A.01.%%'   --上交所科创板股票
                  or AccountCode like '1102.31.01.%%'   --深交所股票
                 or AccountCode like '1102.61.01.%%' )  --深交所创业板股票
        
        '''
    elif assetType == 'cb':
        assetsql = '''
                   (AccountCode like '1103.04.01.%%'   -- 上交所转债
                  or AccountCode like '1103.34.01.%%' )   -- 深交所转债
        '''
    elif assetType == 'bond':
        assetsql = '''
        		  (AccountCode like '1103.01.01.%%'   -- 上交所国债
                 or AccountCode like '1103.31.01.%%' )   -- 深交所国债
        '''
    
    
    
    if enddate is None:
        str_sql = '''
                SELECT  %s
                  FROM [DataCenter].[dbo].[FundPositionHuangyue]
                  where FInnerCode = %s 
                  and %s
                  and FDate >= '%s'
                '''% (str_columns,strFInnerCode, assetsql, begdate)
    else:
        str_sql = '''
                SELECT  %s
                  FROM [DataCenter].[dbo].[FundPositionHuangyue]
                  where FInnerCode = %s 
                  and %s
                  and FDate between '%s' and '%s'
                '''% (str_columns,strFInnerCode, assetsql,begdate,enddate)
                
    cursor.execute(str_sql)
    
    tmp_table = pd.DataFrame(cursor.fetchall(), columns=list_columns)\
        .astype({'FDate':'datetime64[ns]','Volumn':int})           

    return tmp_table

# %% 数据读取

# 设置日期
anadate = get_enddate()
# anadate = datetime.datetime(2025,10,16)
stranadate = anadate.strftime('%Y-%m-%d')


# （1）现有持仓数据
manual_on = False
if manual_on:
    # 手动导入现有持仓数据
    holdingdata = pd.read_excel('data\\转债持仓.xlsx')
    # 增加价格、评级等信息
    holdingdata = pd.merge(holdingdata, anadata[anadata['date'] == anadata['date'].max()]\
                           [['BondCode_wind', 'CreditRating', 'CBPrice']],
                           left_on='证券代码', right_on='BondCode_wind').drop(columns=['证券代码'])
else:    
    conn_zs = pymssql.connect(host=server_zs, database="DataCenter", charset='utf8')
    cursor_zs = conn_zs.cursor()
    holdingdata = get_holding_data(cursor = cursor_zs, FInnerCode = 95, assetType = 'cb', begdate = stranadate, enddate = stranadate)
    # 关闭服务器
    cursor_zs.close()
    conn_zs.close()
    holdingdata = holdingdata[['SecCode','AccountName','Volumn']]\
        .rename(columns = {'SecCode':'证券代码','AccountName':'证券名称','Volumn':'持仓'})
    # 增加价格、评级等信息
    holdingdata = pd.merge(holdingdata, anadata[anadata['date'] == anadata['date'].max()]\
                           [['BondCode','BondCode_wind', 'CreditRating', 'CBPrice']],
                           left_on='证券代码', right_on='BondCode').drop(columns=['证券代码','BondCode'])

# （2）规模数据
dfremainScale = pd.read_excel('data\\remainScale.xlsx')

# （3）标准券质押比例
standardRatio = pd.read_excel('data\\标准券折算比例.xlsx')

# %% 
# 按照平价分组
anadata['group_raw'] = ((anadata['ParPrice']+10)/20).astype(int)-3
anadata.loc[anadata[anadata['group_raw']<0].index,'group_raw'] = 0   # 平价小于70
anadata.loc[anadata[anadata['group_raw']>=4].index,'group_raw'] = 5   # 平价大于130
anadata.loc[anadata[(anadata['CBPrice'] <= 170) & (anadata['group_raw']>=4)].index,'group_raw'] = 4

anadata = anadata.sort_values(by=['InnerCode','date']).reset_index(drop=True)
# anadata['group'] = anadata.groupby(['InnerCode'])['group_raw'].apply(lambda x: x.shift(1))
# anadata['group'] = anadata['group'].fillna(2)
anadata['group'] = anadata['group_raw']

# 按照债性股性分组
# 债性
tmpindex = anadata[(anadata['ParPrice'] <= 70) & (anadata['YTM_wind'] >= -1)].index
anadata.loc[tmpindex,'style'] = 0
# 平衡型
tmpindex = anadata[((anadata['ParPrice'] >= 70) & (anadata['ParPrice'] <= 120) & (anadata['CBPrice'] <= 135))|
                     ((anadata['ParPrice'] <= 70) & (anadata['YTM_wind'] < -1))].index
anadata.loc[tmpindex,'style'] = 1
# 股性
tmpindex = anadata[(anadata['ParPrice'] >= 120) | (anadata['CBPrice'] >= 135)].index
anadata.loc[tmpindex,'style'] = 2



'''
anadata1用于条件筛选，不可用于数据查询
'''


anadata1 = anadata.copy(deep=True)

# (1) 修正转股溢价率因子
# 将修正转股溢价率变为因子格式：按照平价分组，日内计算分位数
anadata1['PremiumRate_adj_factor'] = \
    anadata1[['PremiumRate_adj','date','group']].groupby(['date', 'group'])['PremiumRate_adj'].apply(lambda x: x.rank()/x.count())


# 先将用于计算收益率的数据往前移动
anadata1['date_shift'] = anadata1.groupby('InnerCode')['date'].shift(-1)
anadata1['ret_shift'] = anadata1.groupby('InnerCode')['ret'].shift(-1)


# 剔除赎回进度达到0.5的转债
anadata1 = anadata1[(anadata1['CBClause_Call_finalstate'] < 0.5)]   

anadata1 = anadata1[anadata1['StockPrice'] >= 2]   # 股价大于2的
anadata1 = anadata1[anadata1['YTM_wind']<=5]    # YTM小于5
anadata1['Time2Maturity'] = (anadata1['EndDate'] - anadata1['date'])/d1
anadata1 = anadata1[anadata1['Time2Maturity']>=180]    # 剩余期限大于180个日历日
anadata1['Time2list'] = (anadata1['date'] - anadata1['ListedDate'])/d1
anadata1 = anadata1[anadata1['Time2list']>=10]    # 上市时间超过10个交易日
anadata1 = anadata1[anadata1['RemainScale']>=3*100000000]   # 剩余规模大于3E

# 将日期、收益率变为第二天的结果
anadata1['raw_ret'] = anadata1['ret']
anadata1['raw_date'] = anadata1['date']

anadata1['ret'] = anadata1['ret_shift']
anadata1['date'] = anadata1['date_shift']


# %% 参数设置


remainScale = dfremainScale[dfremainScale['date'] > anadate].sort_values(by='date',ascending = False).iloc[-1]['scale']

checkcolumns = ['date','BondCode_wind','BondAbbr','Sector',
                'CBPrice','ParPrice','PremiumRate','CBinduName','YTM_wind',
                'CreditRating','RemainScale',
                'CBClause_Call_finalstate']


# 非激进转债让渡4%的仓位，以供二级资本债的申购

AAApara = 0.25
nonAAApara1 = 0.20  # 非激进转债
nonAAApara2 = 0.25  # 激进转债

sell_AAA = 1   # 可以卖出AAA转债

# 不投资的债券代码
delbondcode = ['127049.SZ',     # 希望转2
               '113681.SH',     # 镇洋转债
               '123092.SZ',     # 天壕转债
               '111016.SH',     # 神通转债
               '127064.SZ',     # 杭氧转债
               '127022.SZ',     # 恒逸转债
               '113671.SH',     # 武进转债     赎回风险过后再买
               '123212.SZ',     # 立中转债     赎回风险过后再买
               '127060.SZ',     # 湘佳转债     没有入库，也没啥好买的
               '123188.SZ'     # 水羊转债    业绩比较差
               ]

# 需要保留的AAA转债代码
savbondcode = ['110067.SH',      # 华安转债
               '110085.SH',      # 通22转债
               '127110.SZ',      # 广核转债
               #'113066.SH'      # 平煤转债
               ]


# %% 择券
'''AAA转债择券'''
CBAAA = anadata1[anadata1['CreditRating'] == 'AAA']
CBAAA = CBAAA[CBAAA['raw_date'] == anadate]

AAAlowallCB = CBAAA[(CBAAA['PremiumRate_adj_factor']<=0.4) & (CBAAA['group']<=4) \
                        & (CBAAA['CreditRating'] == 'AAA')]\
        [checkcolumns]

'''非AAA转债转债'''
CBnonAAA = anadata1[(anadata1['raw_date'] == anadate) & ((anadata1['CreditRating'] != 'AAA'))]
CBnonAAA = CBnonAAA[CBnonAAA['CreditRating'].isin(['AA+','AA','AA-','A+'])]

nonAAAlowCB = CBnonAAA[(CBnonAAA['PremiumRate_adj_factor']<=0.4) & (CBnonAAA['group'].isin([1,2,3]))]\
    [checkcolumns]
 
'''股性转债'''
stockCB = anadata1[(anadata1['raw_date'] == anadate) & (anadata1['CreditRating'].isin(['AA+','AA','AA-','AAA','A+']))]
stockCB = stockCB[stockCB['style'] == 2]
# 选取溢价率最低的一半转债
stockCB = stockCB[stockCB['PremiumRate'] <= stockCB['PremiumRate'].quantile(0.75)]
# stockCB = stockCB[stockCB['CBPrice'] <= 170]
stockCB = stockCB[checkcolumns]
# 从中剔除其他策略的转债
tmpindex = stockCB[stockCB['BondCode_wind'].isin(nonAAAlowCB['BondCode_wind'])].index
stockCB = stockCB.drop(index = tmpindex)

'''计算每支转债的占比'''
add_columns = ['BondCode_wind','BondAbbr', 'CBPrice','ParPrice','PremiumRate','CreditRating','CBClause_Call_finalstate']

# AAA转债
AAACB = AAAlowallCB[['BondCode_wind']]
AAACB = pd.merge(AAACB, anadata[anadata['date'] == anadate][add_columns], on='BondCode_wind', how='left')


# 需要删去的转债
tmpindex = AAACB[(1- AAACB['BondCode_wind'].isin(delbondcode).astype(int)).astype(bool)].index
AAACB = AAACB.loc[tmpindex]

# 需要增加的转债
addCB = list(set(savbondcode) - set(AAACB['BondCode_wind']))
addCB = anadata[(anadata['date'] == anadate) & (anadata['BondCode_wind'].isin(addCB))][add_columns]
AAACB = pd.concat([AAACB, addCB])


AAACB['holdingRatio'] = AAApara/AAACB.shape[0]

# 非AAA的转债策略
nonAAAstraCB = nonAAAlowCB[['BondCode_wind']]
nonAAAstraCB = pd.merge(nonAAAstraCB, anadata[anadata['date'] == anadate][add_columns], on='BondCode_wind', how='left')

tmpindex = nonAAAstraCB[(1- nonAAAstraCB['BondCode_wind'].isin(delbondcode).astype(int)).astype(bool)].index
nonAAAstraCB = nonAAAstraCB.loc[tmpindex]

nonAAAstraCB['holdingRatio'] = nonAAApara1/nonAAAstraCB.shape[0]

# 非AAA的弹性策略
aggressiveCB = stockCB[['BondCode_wind']]
aggressiveCB = pd.merge(aggressiveCB, anadata[anadata['date'] == anadate][add_columns], on='BondCode_wind', how='left')

tmpindex = aggressiveCB[(1- aggressiveCB['BondCode_wind'].isin(delbondcode).astype(int)).astype(bool)].index
aggressiveCB = aggressiveCB.loc[tmpindex]

aggressiveCB['holdingRatio'] = nonAAApara2/aggressiveCB.shape[0]

# 合并
allCB = pd.concat([AAACB, nonAAAstraCB, aggressiveCB])

allCB = pd.merge(allCB.groupby('BondCode_wind')['holdingRatio'].sum(),
         allCB.set_index('BondCode_wind')[['BondAbbr','CBPrice','PremiumRate','CreditRating','CBClause_Call_finalstate']].drop_duplicates(),
         how='left', left_index = True, right_index = True)

# 增加现有持仓数据
allCB = pd.merge(allCB, holdingdata[['BondCode_wind','证券名称','CBPrice','CreditRating','持仓']].rename(columns={'证券名称':'BondAbbr'}), 
                 left_on=['BondCode_wind','CBPrice','CreditRating', 'BondAbbr'], 
                 right_on=['BondCode_wind','CBPrice','CreditRating', 'BondAbbr'], 
                 how = 'outer')

# 补充缺失数据
# 需要补充的数据index
tmpindex = allCB[allCB['holdingRatio'].isna()].index

# 补充赎回进度
tmpallCB = allCB.loc[tmpindex, :]
tmpallCB = tmpallCB.drop(columns=['CBClause_Call_finalstate','PremiumRate'])
tmpallCB = pd.merge(tmpallCB, anadata[anadata['date'] == anadate][['BondCode_wind','CBClause_Call_finalstate','PremiumRate']],
                    left_on='BondCode_wind', right_on='BondCode_wind', how='left')

allCB  = allCB.drop(index = tmpindex)
allCB = pd.concat([allCB, tmpallCB]).reset_index(drop=True)

allCB['持仓'] = allCB['持仓'].fillna(0)
allCB['holdingRatio'] = allCB['holdingRatio'].fillna(0) 
allCB['持仓amt'] = allCB['持仓'] * allCB['CBPrice']

'''
合并后数据处理
'''
allCB['remainScale'] = remainScale
# 持仓额
allCB['holdingamt'] = allCB['remainScale'] * allCB['holdingRatio']
# 持仓量
allCB['holdingvol'] = allCB['holdingamt'] / allCB['CBPrice']
allCB['holdingvol'] = allCB['holdingvol'].fillna(0)
# 持仓变化情况
allCB['Changevol'] = allCB['holdingvol'] - allCB['持仓']
allCB['Changeamt'] = allCB['Changevol'] * allCB['CBPrice']



'''
如果在AAA转债不能解质押的时候，出现了基金赎回的情况，则AAA转债持仓不动，相应的头寸暂时先卖出非AAA的转债
'''
if sell_AAA == 0:
    # （1）计算AAA转债需要卖出的头寸
    allCBAAA = allCB[allCB['CreditRating'] == 'AAA']
    sell_amt = allCBAAA['Changeamt'].sum()   # 需要卖出的金额
    sell_ratio = sell_amt/remainScale   # 需要卖出的占比
    
    # （2）转化成非AAA转债的相应比例
    tmpindex = allCB[(allCB['CreditRating'] != 'AAA') & (allCB['holdingamt'] > 0)].index
    
    sell_num = len(tmpindex)   # 计划持仓中的非AAA转债数量
    sell_single_ratio = sell_ratio/sell_num   # 单券需要变化的比例
    
    
    '''数据重新处理'''
    # 非AAA的数据修改
    allCB.loc[tmpindex, 'holdingRatio'] = allCB.loc[tmpindex, 'holdingRatio'] - sell_single_ratio
    allCB['holdingamt'] = allCB['remainScale'] * allCB['holdingRatio']
    # 持仓量
    allCB['holdingvol'] = allCB['holdingamt'] / allCB['CBPrice']
    allCB['holdingvol'] = allCB['holdingvol'].fillna(0) 
    
    # AAA的数据修改
    tmpindex = allCB[(allCB['CreditRating'] == 'AAA')].index
    allCB.loc[tmpindex, 'holdingRatio'] = nan
    allCB.loc[tmpindex, 'holdingamt'] = allCB.loc[tmpindex, '持仓amt']
    allCB.loc[tmpindex, 'holdingvol'] = allCB.loc[tmpindex, '持仓']
    

    # 持仓变化情况
    allCB['Changevol'] = allCB['holdingvol'] - allCB['持仓']
    allCB['Changeamt'] = allCB['Changevol'] * allCB['CBPrice']
    
    # allCB = allCB[allCB['CreditRating'] != 'AAA']
    
    


# %% 列名处理
allCB['证券代码'] = allCB['BondCode_wind'].apply(lambda x: x[:6])
allCB['委托方向'] = (1-allCB['Changevol']/allCB['Changevol'].abs())/2+3    # 债券买入3，债券卖出4；提交质押T，转回质押U
allCB['委托方向'] = allCB['委托方向'].fillna(3)

allCB['指令数量'] = allCB['Changevol'].abs()
allCB['指令价格'] = 0
allCB['价格模式'] = nan
allCB['交易市场内部编号'] = allCB['BondCode_wind'].apply(lambda x: x[-2:]).replace({'SH':1,'SZ':2})

singlelimit = 10000000  # 1000w
save_columns = ['证券代码','委托方向','指令数量','指令价格','价格模式','交易市场内部编号']




# %% 质押券处理
# 打印AAA占比：
print('#'*30)
print('AAA转债原有占比：')
print(allCB.groupby('CreditRating')['持仓amt'].sum()/remainScale)
print('#'*30)
print('AAA转债目标占比：')
print(allCB.groupby('CreditRating')['holdingamt'].sum()/remainScale)

# 计算上交所、深交所的目标标准券数量
leveldata = pd.merge(allCB[allCB['CreditRating'] == 'AAA'][['BondCode_wind','CBPrice','holdingvol']], 
                     standardRatio, right_on = '代码', left_on = 'BondCode_wind', how='left')

leveldata['exchange'] = leveldata['BondCode_wind'].apply(lambda x: x[7:])
leveldata['level'] = leveldata['holdingvol'] * leveldata['标准券折算比例']

level_sh = leveldata.groupby('exchange')['level'].sum()['SH'] + 9800000 + 49000000 + 60760000
level_sz = leveldata.groupby('exchange')['level'].sum()['SZ']

print('#'*30)
print('上交所可借钱：' + str(round(level_sh/10000000,3)) +'kw')
print('深交所可借钱：' + str(round(level_sz/10000000,3)) +'kw')
print('#'*30)

# 计算今日交易情况
tradesum = (allCB.groupby(['CreditRating','委托方向'])['Changeamt'].sum()/ 10000)
tradesum = tradesum.reset_index()
tradesum['委托方向'] = tradesum['委托方向'].replace({3:'买入', 4:'卖出'})
tradesum = tradesum.pivot(index = 'CreditRating', columns = '委托方向', values = 'Changeamt').fillna(0)

tradesum_nonAAA = tradesum.sum() - tradesum.loc['AAA']
tradesum_nonAAA = tradesum_nonAAA.to_frame().T
tradesum_nonAAA.index = ['nonAAA']

tradesum_all = tradesum.sum()
tradesum_all = tradesum_all.to_frame().T
tradesum_all.index = ['all']

tradesum  = pd.concat([tradesum , tradesum_nonAAA , tradesum_all ])

print(tradesum)

# %% 整理成下单文件

allCB = allCB[allCB['Changevol'] != 0]

# 1、 AAA转债
allCBAAA = allCB[allCB['CreditRating'] == 'AAA']

# AAA转债下单需要将下单量进行四舍五入至10股的倍数
allCBAAA['指令数量'] = allCBAAA['指令数量'].apply(lambda x: round(x/10,0)*10)

# 每隔singlelimit，进行一次拆分与合并
# 分开买券与卖券，各自排序：先操作小单子，再操作大单，因为大单占用资金时间更长，会导致后面下单等待时间久
allCBAAA_buy = allCBAAA[allCBAAA['Changevol'] > 0].sort_values(by='Changeamt').reset_index(drop= True)
allCBAAA_sell = allCBAAA[allCBAAA['Changevol'] < 0].sort_values(by='Changeamt', ascending = False).reset_index(drop= True)
# 计算累计金额变化
allCBAAA_buy['aculmulateamt'] = allCBAAA_buy['Changeamt'].cumsum()
allCBAAA_sell['aculmulateamt'] = allCBAAA_sell['Changeamt'].cumsum()
# 分组
allCBAAA_buy['group'] = (allCBAAA_buy['aculmulateamt']/singlelimit).astype(int)
allCBAAA_sell['group'] = (allCBAAA_sell['aculmulateamt'].abs()/singlelimit).astype(int)
# 合并
allCBAAA = pd.concat([allCBAAA_buy, allCBAAA_sell])

# （1）买券
allCBAAA_buy = allCBAAA[allCBAAA['委托方向'] == 3]
# （2）提交质押
allCBAAA_T = allCBAAA[allCBAAA['委托方向'] == 3]
allCBAAA_T['委托方向'] = 'T'
# （3）解质押
allCBAAA_U = allCBAAA[allCBAAA['委托方向'] == 4]
allCBAAA_U['委托方向'] = 'U'
# （4）卖券
allCBAAA_sell = allCBAAA[allCBAAA['委托方向'] == 4]



# 2、非AAA转债：每隔singlelimit，进行一次拆分与合并
allCBnonAAA = allCB[allCB['CreditRating'] != 'AAA']

# 分开买券与卖券，各自排序：先操作小单子，再操作大单，因为大单占用资金时间更长，会导致后面下单等待时间久
allCBnonAAA_buy = allCBnonAAA[allCBnonAAA['Changevol'] > 0].sort_values(by='Changeamt').reset_index(drop= True)
allCBnonAAA_sell = allCBnonAAA[allCBnonAAA['Changevol'] < 0].sort_values(by='Changeamt', ascending = False).reset_index(drop= True)

# # 分开买券与卖券，各自排序：按照价格从高到低
# allCBnonAAA_buy = allCBnonAAA[allCBnonAAA['Changevol'] > 0].sort_values(by='CBPrice', ascending = False).reset_index(drop= True)
# allCBnonAAA_sell = allCBnonAAA[allCBnonAAA['Changevol'] < 0].sort_values(by='CBPrice', ascending = False).reset_index(drop= True)


# 计算累计金额变化
allCBnonAAA_buy['aculmulateamt'] = allCBnonAAA_buy['Changeamt'].cumsum()
allCBnonAAA_sell['aculmulateamt'] = allCBnonAAA_sell['Changeamt'].cumsum()

# 分组
allCBnonAAA_buy['group'] = (allCBnonAAA_buy['aculmulateamt']/singlelimit).astype(int)
allCBnonAAA_sell['group'] = (allCBnonAAA_sell['aculmulateamt'].abs()/singlelimit).astype(int)

# 合并
allCBnonAAA = pd.concat([allCBnonAAA_buy, allCBnonAAA_sell])


# 3、数据输出保存
save_path = '丰利转债调仓文件' + anadate.strftime('%Y%m%d')
if os.path.exists(save_path):
    # 清空文件夹内容
    for file_name in os.listdir(save_path):
        os.remove(save_path+'\\'+file_name)
else:
    # 新建文件夹
    os.mkdir(save_path, 0o755)


# (0) 试算风险
checkdata = allCB[allCB['holdingamt'] > 0]
checkdata = checkdata[checkdata['委托方向'] == 3]
checkdata['指令数量'] = 10

checkdata[save_columns].to_excel(save_path+'\\（0）试算买入' + \
                                 anadate.strftime('%Y%m%d') +('.xlsx' if checkdata.shape[0]>0 else '（空）.xlsx'), index = False)


def save_by_group(tradedf, anadate, save_columns,save_path,filename = ' '):
    for tmpgroup in tradedf['group'].unique():
        tmptradedf = tradedf[tradedf['group'] == tmpgroup]
        tmptradedf[save_columns].to_excel(save_path+'\\'+ filename + \
                                          anadate.strftime('%Y%m%d') + '_' +str(tmpgroup) +('.xlsx' if tradedf.shape[0]>0 else '（空）.xlsx'), 
                                          index = False)

# （1）AAA买券
save_by_group(allCBAAA_buy, anadate, save_columns, save_path, filename = '（1）AAA买券')

# （2）AAA提交质押
save_by_group(allCBAAA_T, anadate, save_columns, save_path, filename = '（2）AAA提交质押')

# （3）AAA解质押
save_by_group(allCBAAA_U, anadate, save_columns, save_path, filename = '（3）AAA解质押')

# （4）AAA卖券
save_by_group(allCBAAA_sell, anadate, save_columns, save_path, filename = '（4）AAA卖券')

# （5）非AAA下单
save_by_group(allCBnonAAA, anadate, save_columns, save_path, filename = '（5）非AAA交易')

